var GroupManager = function () {
	
	var groupDto = {id:null, code: "", name:"",fId:"",  rank:"", hasChild:"", type:"",isMenu:""};
		
	var fnEditCallback= function(data){//Form表单提交信息
		$("#saveBtn").button("reset");
		$('#groupAddDlg').modal('hide');
		if(data.type=='success') {
			BootstrapDialog.show({
	            title: messages.public_cue_message,
	            message: data.message,
	            buttons: [{
	                label: messages.public_cue_sure,
	                cssClass: 'btn btn-sm btn-primary',
	                action: function(dialog) {
	                	UITree.refresh("tree_2");
	                	GroupManager.reSearch();
	                    dialog.close();
	                }
	            }]
	        });
		} else {
			BootstrapDialog.show({
	            title: messages.public_cue_error,
	            type: BootstrapDialog.TYPE_WARNING,
	            message: data.message,
	            buttons: [{
	                label: messages.public_cue_sure,
	                cssClass: 'btn btn-sm btn-primary',
	                action: function(dialog) {
	                    dialog.close();
	                    GroupManager.reSearch();
	                }
	            }]
	        });
			GroupManager.reSearch();
		}
	};
	var fnRemoveCallback= function(data){//Form表单提交信息
		if(data.type=='success') {
			BootstrapDialog.show({
	            title: messages.public_cue_message,
	            message: messages.public_cue_delSuccess,
	            buttons: [{
	                label: messages.public_cue_sure,
	                cssClass: 'btn btn-sm btn-primary',
	                action: function(dialog) {
	                	UITree.refresh("tree_2");
	                	GroupManager.reSearch();
	                    dialog.close();
	                }
	            }]
	        });
		} else {
			BootstrapDialog.show({
				type: BootstrapDialog.TYPE_WARNING,
	            title: messages.public_cue_error,
	            message: data.message,
	            buttons: [{
	                label: messages.public_cue_sure,
	                cssClass: 'btn btn-sm btn-primary',
	                action: function(dialog) {
	                    dialog.close();
	                }
	            }]
	        });
			
		}
		GroupManager.reSearch();
	};
    return {
    	datatable:"",
        //main function to initiate the module
        init: function () {
        	this.initTree();
        	this.search();
        	this.setListener();
        	this.formSubmit();
        },
        initTree:function(){
        	var doClick = function() {
    			$.ajax({
                    "type": "GET",
                    "cache": false,
                    "async " : false,
                    "url": ctx+"/group/"+UITree.selectedId+"/gettype?now=" + new Date().getTime(), 
                    "success": function(data){
           				$("#treeType").val(data.level);
           				$("#parentIds").val(data.parentIds);
                    }
                });
    			
    			GroupManager.reSearch();
    	   	};
    		UITree.initTree({
    		   	"url" 		: ctx+"/group/getTrees?now="+new Date().getTime(),
    		   	"id"	 	: "tree_2",
    		   	"checkbox"	: false,
    		   	"click"		: doClick,
    		   	"disable"	: false
    	   	});
        },
        search:function(){
        	if (!jQuery().dataTable) {
                return;
            }
            var groupListTable  = $("#groupListTable").dataTable({
                "sAjaxSource": ctx+"/group/search?now=" + new Date().getTime(), 
                /*使用post方式*/
        		"fnServerData": function ( sSource, aoData, fnCallback ) {
        			var postData = {page:1,start:0,rows:10,params:{}};
        			//参数
        			postData.params.parentId = UITree.selectedId == "" ? "-1" : (UITree.selectedId).toString();
        			for(var i=0,size=aoData.length;i<size;i++){
        				if(aoData[i].name=='iDisplayLength'){
        					postData.rows = aoData[i].value;
        				}else if(aoData[i].name=='iDisplayStart'){
        					postData.start = aoData[i].value;
        				}else if(aoData[i].name=='sEcho'){
        					postData.page = aoData[i].value;
        				}
        			}
                    $.ajax({
                        "dataType": 'json',
                        "cache": false,
                        "type": "POST",
                        "url": sSource,
                        "data": postData,
                        "success": function(data, textStatus, jqXHR){
							fnCallback(data.data, textStatus, jqXHR);
						}
                    });
                },
                "aoColumnDefs": [  
					{  
						"data": "code",
					 	"aTargets": [ 0 ]
					},
                    {  
                      "data": "name",
  		              "aTargets": [ 1 ],
                      'bSortable': true
                    },{  
                    	"data": "sortIndex",
     		        	"aTargets": [ 2 ]
                    },{
	                	"aTargets": [ 3 ],  
                		"mRender": function ( data, type, full ) { 
                			var btns =  '';
                			btns += '<button title="'+messages.public_button_edit+'" class="btn btn-sm-table btn-primary" name="edit" target_id="'+full.id+'">编辑</button>';
                			btns += ' <button title="'+messages.public_button_del+'" href="javascript:;" class="btn btn-sm-table btn-danger" name="del" target_id="'+full.id+'">删除</button>';
							//btns +=  Permission.createPermElement('sysArea:list:base','<button title="'+messages.public_button_edit+'" class="btn btn-sm-table btn-primary" name="edit" target_id="'+full.id+'">编辑</button>');
							//btns += Permission.createPermElement('sysArea:list:del',' <button title="'+messages.public_button_del+'" href="javascript:;" class="btn btn-sm-table btn-danger" name="del" target_id="'+full.id+'">删除</button>');
							return btns;
                			
	                	}  
	                }  
                 ]
            });
            datatable = groupListTable;
        },
        reSearch : function(){
        	datatable.fnDraw();
        },
        setListener:function(){
        	jQuery("body").on('click', 'button[class="close"]', function() {
        		GroupManager.reSearch();
        		return false;
        	});
        	
        	jQuery("#newMenuBtn").click(function(){
        		    var level = $("#treeType").val();
        		    var parentIds = $("#parentIds").val();
        		    if(null == level || '' ==level){
        		    	level = '0';
        		    } else {
        		    	level = parseInt(level) + 1;
        		    }
        			groupDto = {id:null, code: "", name:"", parentId:"0", parentIds:"", sortIndex:"", isMenu:"1", permissions:"",level:level};//hasChild:"", 
        			if(UITree.selectedId != null && (UITree.selectedId).toString() != ''){
            			groupDto.parentId = (UITree.selectedId).toString();
            			
            			groupDto.parentIds = parentIds + (UITree.selectedId).toString() + ",";
                	}
        			$("#headTitle").html($("#newMenuBtn").html());
            		GroupManager.removeClass();
            		GroupManager.fInit(groupDto);
        	});

        	$('#groupListTable tbody')
			.on('click', 'button[name="edit"]',function() {
				var id = $(this).attr("target_id");
				GroupManager.eInit(id);
				
			});
			$('#groupListTable tbody')
			.on('click', 'button[name="del"]',function() {
				var id = $(this).attr("target_id");
				GroupManager.remove(id);
			});
        },
        formSubmit:function(){
        	var form1 = $('#editForm');
            form1.validate({
                rules: {
                	code: {
                        minlength: 2,
                        maxlength:20,
                        required: true
                    },
                    name: {
                        minlength: 2,
                        maxlength:20,
                        required: true
                    },
                    sortIndex: {
                        required:true,
                        maxlength:50
                    }
                },submitHandler: function (form) {//提交
                	$("#saveBtn").button("loading");
                	$.ajax({
                        "dataType": 'json',
                        "cache": false,
                        "type": "POST",
                        "url": ctx+"/group/edit?now=" + new Date().getTime(), 
                        "data": $(form).serializeJson(),
                        "success":function(data){
                        	$("#groupAddDlg").modal('hide');
                        	BootstrapDialog.show({
                	            title: messages.public_cue_message,
                	            message: "资料保存成功",
                	            buttons: [{
                	                label: messages.public_cue_sure,
                	                cssClass: 'btn btn-sm btn-primary',
                	                action: function(dialog) {
                	                	UITree.refresh("tree_2");
                	                	GroupManager.reSearch();
                	                    dialog.close();
                	                }
                	            }]
                	        });
                        } 
                    });
                }
            });
        },
        fInit:function(dto){
        	$("#editForm").binddata(dto);
        	$("#groupAddDlg").modal('show');
        },
        eInit:function(id){
        	document.getElementById("headTitle").innerHTML =messages.public_button_edit;
    	    GroupManager.removeClass();
        	$.ajax({
                "type": "GET",
                "cache" : false,
                "url": ctx+"/group/"+id+"/init?now="+new Date().getTime(), 
                "success": function(data){
                	GroupManager.fInit(data);
                }
            });
        },
        showWarn:function(){
    		BootstrapDialog.show({
    			type: BootstrapDialog.TYPE_WARNING,
    			title: messages.public_cue_warning,
    			message: '请先选择上级区域！',
    			buttons: [{
    				label: messages.public_cue_close,
    				cssClass: 'btn btn-sm btn-default',
    				action: function(dialogItself){
    					dialogItself.close();
    				}
    			}]
    		});
        },
        removeClass:function(){
        	//去除Form表单的验证样式
        	$('.form-group','#editForm').removeClass('has-success')
            .removeClass('has-error');
    		 $('span').remove('.help-block');
        },
        remove:function(id){
        	BootstrapDialog.show({
                type: BootstrapDialog.TYPE_WARNING,
                title: messages.public_cue_warning,
                message: messages.public_cue_delSure,
                buttons: [{
                    label: messages.public_cue_close,
                    cssClass: 'btn btn-sm btn-default',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                },{
                    label: messages.public_cue_sure,
                    cssClass: 'btn btn-sm btn-primary',
                    action:function(dialogItself){
                    	$.ajax({
                            "type": "GET",
                            "cache": false,
                            "url": ctx+"/group/delete/"+id, 
                            "success": fnRemoveCallback
                        });
                    	dialogItself.close();
                    }
                }]
            }); 
        	GroupManager.reSearch();
        }
    };

}();